// 作者：徐斐然

require('../common/header/index.css');
require('../common/nav-simple/index.css');

require('../common/header/index.js');
require('../common/nav-simple/index.js');
require('./index.css');

var $ = require('jquery');
var _common_util = require('util/common_util.js');
var _good_service = require('service/good_service');


var page = {

    init : function(query) {
        this.renderHtml(query);
        this.bindEvent();
    },

    renderHtml : function(query) {
        this.renderSearchResult(query);
    },

    renderSearchResult : function(query) {
        _good_service.search(
            query,
            // success
            function(data, msg) {
                var len = data.length;
                var templateHtml = $("<div><div class='good-item'>"+
                                        "<div class='good-img-wrapper'><img class='good-img'></div>"+
                                        "<div class='goot-info'>"+
                                            "<p class='good-name'></p>"+
                                            "<p class='good-price'></p>"+
                                        "</div>"+
                                    "</div></div>");
                for(let i=0; i<len; i++) {
                    templateHtml.find('.good-item').attr('data-src', './detail.html?id=' + data[i].id);
                    templateHtml.find('.good-img').attr('src', '' + data[i].mainImage);
                    templateHtml.find('.good-name').text(data[i].name);
                    templateHtml.find('.good-price').text('￥'+(parseFloat(data[i].price)/100).toFixed(2));
                    $('.goods-wrapper').html($('.goods-wrapper').html() + templateHtml.html());
                }
                $('.goods-wrapper').html($('.goods-wrapper').html() + '<div class="clearfix"></div>');
            },

            //error
            function(data, msg) {
                
            }
        );
    },

    bindEvent : function() {
        this.bindGoodItemsEvent();
    },

    bindGoodItemsEvent : function() {
        $('.goods-wrapper').on('click', '.good-item', function() {
            window.open($(this).attr('data-src'));
        });
    }
};

$(function() {
    var query = _common_util.getQueryVariable('query');
    page.init(query);
})